package com.freedom.sql.jdbc.request;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.sql.jdbc.netty.MyNioSocketChannel;
import com.freedom.sql.jdbc.response.CommonOkPacket;
import com.freedom.sql.jdbc.statemachine.State;
import com.freedom.sql.jdbc.statemachine.StateMachine;
import com.freedom.sql.jdbc.utils.CharsetUtils;
import com.freedom.sql.jdbc.utils.LoggerUtils;

public class SetPacket {
	private static final Logger logger = LogManager.getLogger(SetPacket.class);
	private MyNioSocketChannel channel;
	private byte[] content;
	private int offset;
	private int packetSeq;

	public SetPacket(int _packetSeq, MyNioSocketChannel _channel, byte[] _content, int _offset) {
		packetSeq = _packetSeq;
		channel = _channel;
		content = _content;
		offset = _offset;// 下一次检查点
	}

	public void handle() throws Exception {
		// 还需要检查下一个状态
		State state = StateMachine.check(content, offset);
		switch (state) {
		case NAMES:
			LoggerUtils.debug(logger, "set names");
			setNames(content);
			break;
		case UNKNOWN:
			throw new Exception("unknown set command");
		}
	}

	private void setNames(byte[] content) throws Exception {
		// 提取出内容--->charset & index
		String str;
		if (channel.getCharset() != null) {
			str = new String(content, channel.getCharset());
		} else {
			str = new String(content);
		}
		String[] array = str.split(" ");
		String charset = array[2];
		int ci = CharsetUtils.getIndex(charset);
		// 合法的charset
		if (ci > 0) {
			channel.setCharset(charset);
			channel.setCharsetIndex(ci);
			LoggerUtils.debug(logger, "set charset to be ==" + charset);
			// 发送成功命令
			new CommonOkPacket(channel, packetSeq + 1).handle();
		} else {
			// 失败则发送失败命令
			throw new Exception("Unknown charset '" + charset + "'");
		}

	}

}
